package com.berwin.syncer.views;

import com.berwin.syncer.entry.Syncer;
import com.berwin.syncer.network.TextServer;
import com.berwin.syncer.utils.QRCodeUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class ConnectView extends JFrame {

    private TextServer socketer;


    public ConnectView(TextServer socketer) {
        this.socketer = socketer;
        this.initPanel();
        this.setSize(350, 380);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setAlwaysOnTop(true);
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
    }

    private void initPanel() {
        this.setLayout(new BorderLayout());

        JPanel pnlCenter = new JPanel(new FlowLayout(FlowLayout.CENTER));
        this.add(pnlCenter, BorderLayout.CENTER);

        JLabel lblQRCode = new JLabel();
        this.generateQRCode(lblQRCode, String.format("%s-%d-%d", this.socketer.getIPAddress(), Syncer.PORT_TEXT, Syncer.PORT_FILE));
        pnlCenter.add(lblQRCode);

        JPanel pnlSouth = new JPanel(new BorderLayout());
        this.add(pnlSouth, BorderLayout.SOUTH);

        JPanel pnlSouthCenter = new JPanel(new FlowLayout(FlowLayout.CENTER));
        pnlSouth.add(pnlSouthCenter, BorderLayout.CENTER);

        JTextField tfHost = new JTextField(10);
        tfHost.setText(this.socketer.getIPAddress());
        pnlSouthCenter.add(tfHost);

        pnlSouthCenter.add(new JLabel(":"));

        JTextField tfPort = new JTextField(4);
        tfPort.setText(Syncer.PORT_TEXT + "");
        pnlSouthCenter.add(tfPort);

        JTextField tfPortFile = new JTextField(4);
        tfPortFile.setText(Syncer.PORT_FILE + "");
        pnlSouthCenter.add(tfPortFile);

        JButton btnGenerate = new JButton("刷新");
        pnlSouthCenter.add(btnGenerate);
        btnGenerate.addActionListener(e -> {
            this.generateQRCode(lblQRCode, String.format("%s-%s-%s", tfHost.getText(), tfPort.getText(), tfPortFile.getText()));
        });

        JPanel pnlTip = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JLabel lblTip = new JLabel("手机端使用Syncer扫码连接\r\n请保证在同一局域网");
        pnlTip.add(lblTip);
        pnlSouth.add(pnlTip, BorderLayout.SOUTH);
    }

    private void generateQRCode(JLabel lbl, String text) {
        try {
            BufferedImage qrcodeBuf = QRCodeUtils.encode(text);
            lbl.setIcon(new ImageIcon(qrcodeBuf));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
